<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/5
 * Time: 14:01
 */

namespace common\models;


use common\consts\Consts;
use common\helpers\StringUtil;
use yii\db\QueryInterface;

trait DataTableQueryTrait
{
    /**
     * @param $query QueryInterface
     * @param $query_params array
     * @param $search_columns array 支持模糊查询的列
     * @return QueryInterface
     */
    public function getDtQuery($query, $query_params, $search_columns = null){
        $keywords = '';
        if (key_exists('search', $query_params)){
            $keywords = $query_params['search']['value'];
        }

        if ($search_columns && count($search_columns) > 0){
            $orConditions = ['or'];

            foreach ($search_columns as $col){
                array_push($orConditions, ['like', $col, $keywords]);
            }

            $query->andFilterWhere($orConditions);
        }

        return $query;
    }

    /**
     * @param $query QueryInterface
     * @param $query_params array
     * @return QueryInterface
     */
    public function getDtListQuery($query, $query_params){
        if (!key_exists('start', $query_params)){
            $query_params['start'] = 0;
        }
        if (!key_exists('length', $query_params)){
            $query_params['length'] = Consts::DEFAULT_PAGE_SIZE;
        }

        $sort_column_name = '';
        $sort_type = 'asc';

        if (key_exists('order', $query_params)){
            $sort_column_num = $query_params['order'][0]['column']; //哪一列需要排序
            $sort_column_name = $query_params['columns'][$sort_column_num]['data'];
            $sort_type = $query_params['order'][0]['dir']; //排序方式  asc or desc
        }

        if (!StringUtil::isNullOrWhiteSpace($sort_column_name)){
            $sortVal = Consts::SORT_ORDER_MAP()[$sort_type];
            $query->orderBy([
                $sort_column_name => $sortVal,
            ]);
        }

        $query->offset($query_params['start'])->limit($query_params['length']);
        return $query;
    }
}